package com.hlwxy.ssm.service.impl;

import com.hlwxy.ssm.dao.ExcelTextMapper;
import com.hlwxy.ssm.model.ExcelText;
import com.hlwxy.ssm.service.ExcelTextService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("excelTextService")
public class ExcelTextServiceImpl implements ExcelTextService {


    @Autowired
    private ExcelTextMapper excelTextMapper;

    public HSSFWorkbook exportExcel() {

        //创建一个工作簿
        HSSFWorkbook wb = new HSSFWorkbook();
        try {
            //创建工作表
            HSSFSheet sheet = wb.createSheet("答题信息");
            //创建表头
            HSSFRow headRow = sheet.createRow((short)0);
            headRow.createCell(0).setCellValue("标题");
            headRow.createCell(1).setCellValue("创建时间");
            headRow.createCell(2).setCellValue("答案");
            headRow.createCell(3).setCellValue("创建人");
            List<ExcelText> list=excelTextMapper.findAllExcelText();

            int i=1;
            for(ExcelText excelText:list){
                Row row= sheet.createRow((short)i);
                i++;
                row.createCell(0).setCellValue(excelText.getName());
                row.createCell(1).setCellValue(excelText.getCreateDate());
                row.createCell(2).setCellValue(excelText.getAnswer());
                row.createCell(3).setCellValue(excelText.getCreator());
            }

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return wb;
    }

    public void uploadExcel(HSSFWorkbook workbook) {
        HSSFSheet sheet=workbook.getSheetAt(0);
        System.out.println("当前excel的行数:"+sheet.getLastRowNum());
        List<ExcelText> list=new ArrayList<ExcelText>();
        ExcelText excelText;
        for (int i=1;i<sheet.getLastRowNum()+1;i++){
             Row row= sheet.getRow(i);
             excelText=new ExcelText();
             excelText.setName(row.getCell(0).toString());
             excelText.setCreateDate(row.getCell(1).toString());
             excelText.setAnswer(row.getCell(2).toString());
             excelText.setCreator(row.getCell(3).toString());
             list.add(excelText);
             //System.out.println(row.getCell(0).toString()+row.getCell(1).toString()+row.getCell(2).toString()+row.getCell(3).toString());
        }
        excelTextMapper.addBatchExcelText(list);
    }
}
